//
//  UIApplication+Extension.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/3.
//


import UIKit

extension UIApplication : LXSExtensionCompatible {}
extension UIWindow: LXSExtensionCompatible {}

public extension LXS where Base: UIApplication {
    
    // MARK: 获取顶层控制器 根据window
    static var topViewController: UIViewController? {
        //是否为当前显示的window
        return topWindow.lxs.topViewController
    }
    
    // MARK: 获取最上层显示的window
    static var topWindow: UIWindow {
        let windows = UIApplication.shared.windows
        var ignoreWindowsClass = [AnyClass]()
        if let UIRemoteKeyboardWindow = NSClassFromString("UIRemoteKeyboardWindow") {
            ignoreWindowsClass.append(UIRemoteKeyboardWindow)
        }
        if let YYTextEffectWindow = NSClassFromString("YYTextEffectWindow") {
            ignoreWindowsClass.append(YYTextEffectWindow)
        }
        if let UITextEffectsWindow = NSClassFromString("UITextEffectsWindow") {
            ignoreWindowsClass.append(UITextEffectsWindow)
        }
        if let FLEXWindow = NSClassFromString("FLEXWindow") {
            ignoreWindowsClass.append(FLEXWindow)
        }
        let topWindow = windows.last { window in
            if window.bounds.equalTo(UIScreen.main.bounds) == true,
               window.isHidden == false,
               window.windowLevel == UIWindow.Level.normal {
                let index = ignoreWindowsClass.firstIndex { clas in
                    window.isKind(of: clas)
                }
                debugLog(window.isKeyWindow)
                if index != nil {
                    return false
                }
                return true
            }
            return false
        }
        if let window = topWindow {
            debugLog(window)
            return window
        }
        return UIApplication.shared.keyWindow ?? UIApplication.shared.delegate!.window!!
    }
    // MARK: 获取TabBarController
    static var topTabBarController: UITabBarController? {
        
        return topWindow.lxs.currentTabBarController
    }
    ///设置tabbar角标
    static func setTabBarbadge(index : Int,badge : Int){
        let vc = UIApplication.shared.delegate?.window??.lxs.currentTabBarController
        if  badge > 0 {
            if badge > 99{
                vc?.viewControllers?[index].tabBarItem.badgeValue = "99+"
            }else{
                vc?.viewControllers?[index].tabBarItem.badgeValue = "\(badge)"
            }
        }else{
            vc?.viewControllers?[index].tabBarItem.badgeValue = nil
        }
    }
    
    // MARK: 获取NavigationController

    static var topNavigationController: UINavigationController? {
        topWindow.lxs.topNavigationController
    }

    static func callTel(_ tel: String) {
        var array = tel.components(separatedBy: ";")
        let charset = CharacterSet(charactersIn: ",")
        if tel.rangeOfCharacter(from: charset) != nil {
            array = tel.components(separatedBy: ",")
        }
        if array.count > 1 {
//            let alert = Alert.with(title: "请选择", style: .actionSheet)
//                .bind(button: "取消", style: .cancel, handler: nil)
//            array.forEach({ tel in
//                if tel.isEmpty == false{
//                    alert.bind(button: tel) { _ in
//                        callTel(tel)
//                    }
//                }
//            })
//            alert.show()
//            let alert = Alert.with(style: "请选择", type: .actionSheet)
        } else {
            let phone = "telprompt://" + tel
            let url = URL(string: phone, ignoreEncodedCharacters: nil)!
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }

    // MARK: 跳转到APP系统设置权限界面
    static func goSystemPrivacySetting() {
        guard let appSetting = URL(string: UIApplication.openSettingsURLString) else {
            return
        }
        if #available(iOS 10, *) {
            UIApplication.shared.open(appSetting, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(appSetting)
        }
    }
    
    static func exit() {
        
        Darwin.exit(0)
        
//        guard let app = UIApplication.shared.delegate, let window = app.window! else {
//            Darwin.exit(0)
//        }
//        UIView.animate(withDuration: 0.1) {
//            window.alpha = 0
//            window.frame = CGRect(x: 0, y: window.bounds.width, width: window.bounds.width, height: window.bounds.height)
//        } completion: { isFinished in
//            Darwin.exit(0)
//        }

    }
}

public extension LXS where Base: UIWindow {
    var topViewController: UIViewController? {
        //是否为当前显示的window
        return topViewControllerBy(base.rootViewController)
    }
    
    private func topViewControllerBy(_ viewController :UIViewController?) -> UIViewController? {
        guard let viewController = viewController else {
            debugLog("找不到顶层控制器")
            return nil
        }
        if let presentVC = viewController.presentedViewController {
            // modal出来的 控制器
            return topViewControllerBy(presentVC)
        }
        else if let tabVC = viewController as? UITabBarController {
            if let selectVC = tabVC.selectedViewController {
                return topViewControllerBy(selectVC)
            }
            return nil
        } else if let naiVC = viewController as? UINavigationController {
            return topViewControllerBy(naiVC.visibleViewController)
        } else {
            return viewController
        }
    }
    
    // MARK: 获取TabBarController
    var currentTabBarController: UITabBarController? {
        
        if let rootViewController = base.rootViewController as? UITabBarController {
            return rootViewController
        }
        return nil
    }
    
    var topNavigationController: UINavigationController? {
        var nac = topViewController?.navigationController
        if nac == nil || nac?.isKind(of: UIImagePickerController.self) == true {
            // 需要排除掉UIImagePickerController
            nac = currentTabBarController?.selectedViewController as? UINavigationController
        }
        return nac
    }
}

